﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using Managistics.Warehouse.Views.Interfaces;
using Managistics.Model;
using Managistics.Core;
using Managistics.Core.Services;
using Managistics.Utility.Common;
using BrightIdeasSoftware;
using Managistics.Utility.Common.View.Components;

namespace Managistics.Warehouse.Views.Purchases
{
    public partial class ViewEnterInputSheet : MetroForm, IViewEnterInputSheetView
    {
        private string InputSheetId;
        private string[] listGoodAutocomplete;
        private List<InputSheetDetailVO> listInputSheetDetailVO;

        public ViewEnterInputSheet()
        {
            InitializeComponent();
            InitializeGridInputSheet();
            InitializeData();

            base.Closed += delegate { Closed(); };
        }

        ///
        /// =======================================================================================
        /// Initialize datas
        /// =======================================================================================
        ///
        private void InitializeData()
        {            
            this.LoadAllInputSheets();
            this.metroComboBox2.DataSource = GlobalApp.ListInputSheetTypes;
            this.metroComboBox3.DataSource = GlobalApp.AllSuppliers;
            this.metroComboBox4.DataSource = GlobalApp.AllCustomers;
            List<string> listGoodStr = new List<string>();
            foreach (Good g in GlobalApp.AllGoods)
            {
                listGoodStr.Add(g.Code);
            }
            listGoodAutocomplete = listGoodStr.ToArray();

            this.listInputSheetDetailVO = new List<InputSheetDetailVO>();            
            InputSheetDetailVO newRowObj = new InputSheetDetailVO();
            this.listInputSheetDetailVO.Add(newRowObj);
            this.gridInputSheet.AddObjects(this.listInputSheetDetailVO);
            this.gridInputSheet.EnsureModelVisible(newRowObj);

        }

        ///
        /// =======================================================================================
        /// Implements Actions from IViewEnterInputSheetView
        /// =======================================================================================
        ///
        public void Open()
        {
            ShowDialog();
        }
        public void Open(IView view)
        {
            return;
        }
        public new event Action Closed = delegate { };
        public event Action LoadAllInputSheets = delegate { };
        public event Action SaveInputSheet = delegate { };

        /// <summary>
        /// Set InputSheet data to InputSheet Combobox
        /// </summary>
        /// <param type="InputSheetRecord" name="record"></param>
        public void SetInputSheetRecord(List<InputSheet> list)
        {
            this.metroComboBox2.DataSource = list;
            if (list != null && list.Count > 0)
            {
                this.metroComboBox2.SelectedIndex = list.Count - 1;
            }
        }

        private void metroComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Onclick Save InputSheet
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void metroButton6_Click(object sender, EventArgs e)
        {
            this.SaveInputSheet();
        }

        /// <summary>
        /// Get parameters
        /// </summary>
        /// <returns></returns>
        public ViewEnterInputSheetParam GetParams()
        {
            ViewEnterInputSheetParam p = new ViewEnterInputSheetParam();
            p.InputSheetType = (CfgInputSheetType)this.metroComboBox2.SelectedItem;
            p.Supplier = (Supplier)this.metroComboBox3.SelectedItem;
            p.Customer = (Customer)this.metroComboBox4.SelectedItem;
            p.Department = this.metroTextBox13.Text;
            p.Description = this.metroTextBox9.Text;
            p.inputDate = DateTimeWithZone.string2DateTime(this.metroTextBox12.Text);            
            p.Receiver = this.metroTextBox10.Text;
            p.Deliver = this.metroTextBox11.Text;
            p.InputSheetId = this.InputSheetId;
            p.listDetail = this.gridInputSheet.Objects.Cast<InputSheetDetailVO>().ToList<InputSheetDetailVO>(); 

            return p;
        }

        /// <summary>
        /// Setting datas
        /// </summary>
        /// <param name="p"></param>
        public void SetData(ViewEnterInputSheetParam p)
        {
            this.listInputSheetDetailVO = p.listDetail;
            this.metroComboBox2.SelectedItem = p.InputSheetType;
            this.metroComboBox3.SelectedItem = p.Supplier;
            this.metroComboBox4.SelectedItem = p.Customer;
            this.metroTextBox13.Text = p.Department;
            this.metroTextBox9.Text = p.Description;
            this.metroTextBox12.Text = String.Format("{0:dd/MM/yyyy}", p.inputDate);
            this.metroTextBox10.Text = p.Receiver;
            this.metroTextBox11.Text = p.Deliver;
            this.InputSheetId = p.InputSheetId;
            this.gridInputSheet.SetObjects(p.listDetail);

        }

        /// <summary>
        /// Get index for row
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int getRowIndex(InputSheetDetailVO obj)
        {
            if (this.listInputSheetDetailVO == null || this.listInputSheetDetailVO.Count == 0)
                return 1;
            int index = this.listInputSheetDetailVO.IndexOf(obj);
            if (index == -1)
            {
                return this.listInputSheetDetailVO.Count + 1;
            }
            return index + 1;
        }

        /// <summary>
        /// Cell edit starting for InputSheetDetail grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridInputSheetDetail_EditStarting(object sender, CellEditEventArgs e)
        {
            OLVColumn col = (OLVColumn)e.Column;
            if (col.AspectName == "GoodCode")
            {
                TextBox tb = new TextBox();
                tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
                auto.AddRange(listGoodAutocomplete);
                tb.AutoCompleteCustomSource = auto;
                tb.Text = (e.Value == null) ? "" : e.Value.ToString();
                tb.Bounds = e.CellBounds;
                tb.Font = ((ObjectListView)sender).Font;

                tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                tb.AutoCompleteCustomSource.AddRange(listGoodAutocomplete);

                e.Control = tb;
            }

            //OLVColumn col = (OLVColumn)e.Column;
            //if (col.AspectName == "GoodCode")
            //{
            //    ColumnComboBox goodCodeAutoComplete = new ColumnComboBox();
            //    goodCodeAutoComplete.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
            //    goodCodeAutoComplete.DropDownWidth = 17;
            //    //this.goodCodeAutoComplete.Location = new System.Drawing.Point(24, 24);
            //    goodCodeAutoComplete.Name = "goodCodeAutoComplete";
            //    //this.goodCodeAutoComplete.Size = new System.Drawing.Size(176, 21);
            //    goodCodeAutoComplete.TabIndex = 0;
            //    goodCodeAutoComplete.ViewColumn = 0;
            //    //Init and loading data for Good Code autocomplete
            //    System.Data.DataTable myDataTable = new DataTable("ParentTable");
            //    // Declare variables for DataColumn and DataRow objects.
            //    DataColumn goodCodeColumn = new DataColumn();
            //    goodCodeColumn.DataType = typeof(string);
            //    goodCodeColumn.ColumnName = "goodCodeColumn";
            //    //goodCodeColumn.Caption = "ParentItem";
            //    goodCodeColumn.AutoIncrement = false;
            //    goodCodeColumn.ReadOnly = false;
            //    goodCodeColumn.Unique = false;
            //    // Add the Column to the DataColumnCollection.
            //    myDataTable.Columns.Add(goodCodeColumn);

            //    DataColumn goodNameColumn = new DataColumn();
            //    goodNameColumn.DataType = typeof(string);
            //    goodNameColumn.ColumnName = "goodNameColumn";
            //    //goodNameColumn.Caption = "ParentItem";
            //    goodNameColumn.AutoIncrement = false;
            //    goodNameColumn.ReadOnly = false;
            //    goodNameColumn.Unique = false;
            //    // Add the Column to the DataColumnCollection.
            //    myDataTable.Columns.Add(goodNameColumn);

            //    DataColumn goodUnitColumn = new DataColumn();
            //    goodUnitColumn.DataType = typeof(string);
            //    goodUnitColumn.ColumnName = "goodUnitColumn";
            //    //goodUnitColumn.Caption = "ParentItem";
            //    goodUnitColumn.AutoIncrement = false;
            //    goodUnitColumn.ReadOnly = false;
            //    goodUnitColumn.Unique = false;
            //    // Add the Column to the DataColumnCollection.
            //    myDataTable.Columns.Add(goodUnitColumn);

            //    DataRow myDataRow;
            //    foreach (Good g in GlobalApp.AllGoods)
            //    {
            //        myDataRow = myDataTable.NewRow();
            //        myDataRow["goodCodeColumn"] = g.Code;
            //        myDataRow["goodNameColumn"] = g.Name;
            //        myDataRow["goodUnitColumn"] = g.UnitItem.Name;
            //        myDataTable.Rows.Add(myDataRow);
            //    }

            //    //Now set the Data of the ColumnComboBox
            //    goodCodeAutoComplete.Data = myDataTable;
            //    //Set which row will be displayed in the text box
            //    //If you set this to a column that isn't displayed then the suggesting functionality won't work.
            //    //this.goodCodeAutoComplete.ViewColumn = 1;
            //    //Set a few columns to not be shown
            //    goodCodeAutoComplete.Columns[2].Display = false;//goodUnitColumn

            //    goodCodeAutoComplete.CellEditSender = null;
            //    goodCodeAutoComplete.Bounds = e.CellBounds;
            //    goodCodeAutoComplete.Font = ((ObjectListView)sender).Font;
            //    goodCodeAutoComplete.CellEditSender = sender;
            //    goodCodeAutoComplete.SelectedIndexChanged += new System.EventHandler(this.goodCodeAutoComplete_SelectedIndexChanged);

            //    e.Control = goodCodeAutoComplete;
            //} 
        }

        //private void goodCodeAutoComplete_SelectedIndexChanged(object sender, System.EventArgs e)
        //{
        //    ColumnComboBox ccbb = (ColumnComboBox)sender;
        //    //You can get data from the selected row out of the ColumnComboBox like this:
        //    if (this.goodCodeAutoComplete.SelectedIndex > -1)//If there is no selected index the indexer will return null
        //    {
        //        ObjectListView olv = (ObjectListView)ccbb.CellEditSender;
        //        InputSheetDetailVO vo = (InputSheetDetailVO)olv.SelectedObject;
        //        vo.GoodCode = ccbb["goodCodeColumn"].ToString();
        //        vo.GoodName = ccbb["goodNameColumn"].ToString();
        //        vo.Unit = ccbb["goodUnitColumn"].ToString();

        //        olv.RefreshItem(olv.SelectedItem);
                
        //    }
        //}

        /// <summary>
        /// Cell edit finishing for InputSheetDetail grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridInputSheetDetail_EditFinishing(object sender, CellEditEventArgs e)
        {
            this.indexInputSheet = 0;
            OLVColumn col = (OLVColumn)e.Column;
            if (col.AspectName == "Quantity")
            {
                ((InputSheetDetailVO)e.RowObject).Quantity = float.Parse(e.NewValue.ToString());
                ((ObjectListView)sender).RefreshItem(e.ListViewItem);
            }
            this.addNewRowGridInputSheetDetail(sender, e);            
            
            // We have updated the model object, so we cancel the auto update
            e.Cancel = true;

        }

        /// <summary>
        /// Add new row for InputSheetDetail grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addNewRowGridInputSheetDetail(object sender, CellEditEventArgs e)
        {
            InputSheetDetailVO item = (InputSheetDetailVO)e.RowObject;
            int index = getRowIndex(item);
            int end = this.listInputSheetDetailVO == null ? 1 : this.listInputSheetDetailVO.Count;
            
            if (index == end && !string.IsNullOrEmpty(item.GoodCode) && item.Quantity > 0)
            {
                InputSheetDetailVO newRowObj = new InputSheetDetailVO();
                if (this.listInputSheetDetailVO == null)
                    this.listInputSheetDetailVO = new List<InputSheetDetailVO>();
                this.listInputSheetDetailVO.Add(newRowObj);
                this.gridInputSheet.AddObject(newRowObj);
                //this.gridInputSheet.EnsureModelVisible(newRowObj);
            }
        }
    }

}
